package com.lzhl.buildjar.dao;

import java.sql.*;
import java.util.Set;

/**
 * 数据库访问基类
 * @author 李柱良(@柱子的日月)
 * @date 2014/6/18
 */
public class BaseDao implements Dao {
    private Connection connection;

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    protected void executeUpdate(String sql) throws SQLException {
        PreparedStatement pstmt = null;
        try {
            pstmt = getConnection().prepareStatement(sql);
            pstmt.executeUpdate();
        }
        finally {
            close(pstmt);
        }
    }

    protected boolean isTableExists(String tablename) throws SQLException {
        String sql = "SELECT name FROM sqlite_master WHERE type ='table' and name = ?";

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = getConnection().prepareStatement(sql);
            pstmt.setString(1, tablename);
            rs = pstmt.executeQuery();

            return rs.next();
        }
        finally {
            close(pstmt, rs);
        }
    }

    protected boolean isTableHasData(String tablename) throws SQLException {
        String sql = "SELECT 1 FROM " + tablename + " limit 0,1";

        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = getConnection().prepareStatement(sql);
            rs = pstmt.executeQuery();

            return rs.next();
        }
        finally {
            close(pstmt, rs);
        }
    }

    protected void rollback(Connection conn) {
        if(conn != null) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected void close(Statement stmt) {
        close(stmt, null);
    }

    protected void close(Statement stmt, ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected String getIDSql(String field, Set<String> ids) {
        if(ids.size() == 0) {
            return "";
        }
        else if(ids.size() == 1) {
            return field + " = '" + ids.iterator().next() + "'";
        }
        else {
            StringBuffer sql = new StringBuffer();
            sql.append(field).append(" in (");

            for (String id : ids) {
                sql.append("'").append(id).append("',");
            }
            sql.deleteCharAt(sql.length()-1);

            sql.append(")");

            return sql.toString();
        }
    }

}
